package http_servlet_request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * Creared with IntelliJ IDEA.
 * Description:
 * User:yxd
 * Date:2022-05-29
 * Time:17:51
 */
@WebServlet("/showRequest")
public class MyHttpServletRequest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //调用一下HTTPServletRequest所涉及到的API,把得到的结果组织到html中,并作为响应的body
        //把api得到的结果放到stringBuilder中去,方便后面放入body
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("<h3>下面是首行部分</h3>");

        //得到协议名和版本
        stringBuilder.append("协议名和版本:" + req.getProtocol());
        stringBuilder.append("<br>");
        //得到方法
        stringBuilder.append("方法:" + req.getMethod());
        stringBuilder.append("<br>");
        //得到url(请求路径)
        stringBuilder.append("url:" + req.getRequestURI());
        stringBuilder.append("<br>");
        //得到上下文路径(一级路径)
        stringBuilder.append("context path:" + req.getContextPath());
        stringBuilder.append("<br>");
        //得到query string 有?后面的内容就是query string,没有就是null
        stringBuilder.append("query string:" + req.getQueryString());
        stringBuilder.append("<br>");
        //得到header部分
        stringBuilder.append("<h3>下面是header部分</h3>");
        //枚举
        Enumeration<String> headerNames = req.getHeaderNames();
        //迭代器
        while(headerNames.hasMoreElements()){
            //通过枚举得到每一个key
            String headerName = headerNames.nextElement();
            //再通过每一个key得到对应的value
            String headerValue = req.getHeader(headerName);
            stringBuilder.append(headerName + ":" + headerValue + "<br>");
        }
        //保证不出现乱码  这里的text/html只能写成text/html,不能写成test/html就不能被浏览器识别了
        resp.setContentType("text/html;charset=utf8");
        resp.getWriter().write(stringBuilder.toString());

    }
}
